package org.genntii.warehousesystem.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.comm.SignVersion;
import jakarta.annotation.Resource;
import org.genntii.warehousesystem.common.OssProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

@Component
@PropertySource("classpath:application.yaml")
public class OssUtil {

    @Resource
    private OssProperties ossProperties;

    public String uploadPic(MultipartFile file,String name) {
        String url = null;
        String endPoint = ossProperties.getEndPoint();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        String bucketName = ossProperties.getBucketName();
        String region = ossProperties.getRegion();
        OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);
        try {
            String fileName = name + UUID.randomUUID() + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
            ossClient.putObject(bucketName,fileName,new ByteArrayInputStream(file.getBytes()));
            url = "https://"+bucketName+"."+endPoint+"/"+fileName;
        } catch (IOException e){
            System.out.println(e.getMessage());
        }finally {
            ossClient.shutdown();
        }
        return url;
    }




//    private static final String endPoint = "genntii.oss-cn-hangzhou.aliyuncs.com";
//
//    @Value("${genntii.oss.access-key-id}")
//    private static String accessKeyId;
//
//    @Value("${genntii.oss.access-key-secret}")
//    private static String accessKeySecret;
//
//    private static final String bucketName = "genntii";
//
//    private static final String region = "cn-hangzhou";
//
//    public static String uploadPic(byte[] bytes,String name) throws com.aliyuncs.exceptions.ClientException {
//        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
//        ClientBuilderConfiguration config = new ClientBuilderConfiguration();
//        config.setSignatureVersion(SignVersion.V4);
//        config.setMaxConnections(200);
//        config.setSocketTimeout(10000);
//        config.setConnectionTimeout(10000);
//        config.setConnectionRequestTimeout(10000);
//        config.setIdleConnectionTime(10000);
//        config.setMaxErrorRetry(5);
//        config.setSupportCname(true);
//        config.setSLDEnabled(true);
//        config.setProtocol(Protocol.HTTP);
//
//        OSS ossClient = OSSClientBuilder.create()
//                .endpoint(endPoint)
//                .credentialsProvider(credentialsProvider)
//                .clientConfiguration(config)
//                .region(region)
//                .build();
//
//        try{
//            ossClient.putObject(bucketName,name,new ByteArrayInputStream(bytes));
//        }catch (OSSException oe){
//            System.out.println("Caught an OSSException, which means your request made it to OSS, "
//                    + "but was rejected with an error response for some reason.");
//            System.out.println("Error Message:" + oe.getErrorMessage());
//            System.out.println("Error Code:" + oe.getErrorCode());
//            System.out.println("Request ID:" + oe.getRequestId());
//            System.out.println("Host ID:" + oe.getHostId());
//        }catch (ClientException ce) {
//            System.out.println("Caught an ClientException, which means the client encountered "
//                    + "a serious internal problem while trying to communicate with OSS, "
//                    + "such as not being able to access the network.");
//            System.out.println("Error Message:" + ce.getMessage());
//        } finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
//        }
//        StringBuilder stringBuilder = new StringBuilder("https://");
//        stringBuilder
//                .append(bucketName)
//                .append(".")
//                .append(endPoint)
//                .append("/")
//                .append(name);
//
//
//
//        return stringBuilder.toString();
//    }

}
